package com.roroldo.springcloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义实现的轮询算法
 * @author 落霞不孤
 */
@Component
@Slf4j
public class MyLB implements LoadBalancer{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    // 获取可用服务的下标
    public final int getAndIncrement() {
        int current;
        int next;
        for (;;) {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
            if (atomicInteger.compareAndSet(current, next)) {
                log.info("next 下标为:{}", next);
                return next;
            }
        }
    }
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = (getAndIncrement() - 1) % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
